<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-panel">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="机构名称" prop="hospitalName">
          <el-input
              v-model="queryParams.hospitalName"
              placeholder="请输入机构名称"
              clearable
              @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="机构类型" prop="hospitalType">
          <el-select
              v-model="queryParams.hospitalType"
              placeholder="请选择机构类型"
              clearable
              filterable
          >
            <el-option
                v-for="type in hospitalTypeOptions"
                :key="type.value"
                :label="type.label"
                :value="type.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="机构等级" prop="grade">
          <el-select
              v-model="queryParams.grade"
              placeholder="请选择机构等级"
              clearable
              filterable
          >
            <el-option
                v-for="grade in gradeOptions"
                :key="grade.value"
                :label="grade.label"
                :value="grade.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-panel">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['institution:hospital:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['institution:hospital:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['institution:hospital:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              v-hasPermi="['institution:hospital:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </div>

    <!-- 数据表格 -->
    <div class="table-panel">
      <el-table
          v-loading="loading"
          :data="hospitalList"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="机构名称" align="center" prop="hospitalName" />
        <el-table-column label="机构Logo" align="center" prop="logo" width="80">
          <template #default="scope">
            <div class="logo-container">
              <el-image
                  v-if="scope.row.logo"
                  class="table-logo"
                  :src="scope.row.logo"
                  :preview-src-list="[scope.row.logo]"
                  fit="cover"
                  preview-teleported
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <span v-else class="no-logo">无Logo</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="机构类型" align="center" prop="hospitalType" width="100">
          <template #default="scope">
            <span>{{ formatHospitalType(scope.row.hospitalType) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="地址" align="center" prop="address" min-width="200">
          <template #default="scope">
            <el-tooltip
                :content="getFullAddress(scope.row)"
                placement="top"
                v-if="getFullAddress(scope.row) !== '-'"
            >
              <span class="address-text">
                {{ getFullAddress(scope.row) }}
              </span>
            </el-tooltip>
            <span v-else class="no-address">-</span>
          </template>
        </el-table-column>
        <el-table-column label="机构等级" align="center" prop="grade" width="100">
          <template #default="scope">
            <span>{{ scope.row.grade || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否上架" align="center" prop="status" width="100">
          <template #default="scope">
            <el-switch
                v-model="scope.row.status"
                :active-value="'1'"
                :inactive-value="'0'"
                @change="(value) => handleStatusChange(scope.row, value)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
          <template #default="scope">
            <div class="action-buttons">
              <el-tooltip content="查看详情" placement="top">
                <el-button
                    link
                    type="primary"
                    icon="View"
                    @click="handleView(scope.row)"
                    v-hasPermi="['institution:hospital:query']"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="修改" placement="top">
                <el-button
                    link
                    type="primary"
                    icon="Edit"
                    @click="handleUpdate(scope.row)"
                    v-hasPermi="['institution:hospital:edit']"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button
                    link
                    type="primary"
                    icon="Delete"
                    @click="handleDelete(scope.row)"
                    v-hasPermi="['institution:hospital:remove']"
                ></el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-panel">
      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </div>

    <!-- 查看机构详情对话框 -->
    <el-dialog
        title="机构详情"
        v-model="viewOpen"
        width="800px"
        append-to-body
    >
      <div v-loading="detailLoading" class="detail-content">
        <el-descriptions :column="2" border v-if="viewForm.hospitalId">
          <el-descriptions-item label="机构名称">
            <span>{{ viewForm.hospitalName }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="机构Logo">
            <div class="logo-detail">
              <el-image
                  v-if="viewForm.logo"
                  class="detail-logo"
                  :src="viewForm.logo"
                  :preview-src-list="[viewForm.logo]"
                  fit="cover"
                  preview-teleported
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <span v-else class="no-logo-detail">暂无Logo</span>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="机构类型">
            <span>{{ formatHospitalType(viewForm.hospitalType) }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="机构等级">
            <span>{{ viewForm.grade }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">
            <span>{{ viewForm.contactPhone || '无' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="是否上架">
            <el-tag :type="viewForm.status === '1' ? 'success' : 'danger'">
              {{ viewForm.status === '1' ? '上架' : '下架' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="地址" :span="2">
            <span class="address-detail">
              {{ getFullAddress(viewForm) }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="机构描述" :span="2">
            <span>{{ viewForm.description || '无' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="科室" :span="2">
            <div v-if="getGroupedDepartments().length > 0" class="departments-container">
              <div v-for="primaryDept in getGroupedDepartments()" :key="primaryDept.primaryId" class="department-group">
                <div class="primary-department">{{ primaryDept.primaryName }}：</div>
                <div class="secondary-departments">
                  <el-tag
                      v-for="secondaryDept in primaryDept.secondaryDepartments"
                      :key="secondaryDept.departmentId"
                      size="small"
                  >
                    {{ secondaryDept.departmentName }}
                  </el-tag>
                </div>
              </div>
            </div>
            <span v-else class="no-departments">无关联科室</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Hospital">
import { listHospital, getHospital, delHospital, updateHospital, getHospitalWithDepartments, listPrimaryDepartments, listChildrenDepartments, uploadLogo } from "@/api/institution/hospital"
import { Picture, View } from '@element-plus/icons-vue'
import { getToken } from "@/utils/auth.js"

const { proxy } = getCurrentInstance()

const hospitalList = ref([])
const open = ref(false)
const viewOpen = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
// 添加详情加载状态
const detailLoading = ref(false)

// 添加一级科室名称映射
const primaryDepartmentNames = ref({})

// 下拉框选项
const hospitalTypeOptions = ref([
  { value: 1, label: '医院' },
  { value: 2, label: '体检中心' },
  { value: 3, label: '诊所' }
])
const gradeOptions = ref([])

const data = reactive({
  viewForm: {
    departments: [] // 确保初始化为空数组
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    hospitalName: null,
    hospitalType: null,
    grade: null,
  }
})

const { queryParams, viewForm } = toRefs(data)

/** 查询机构管理列表 */
function getList() {
  loading.value = true
  listHospital(queryParams.value).then(response => {
    hospitalList.value = response.rows
    total.value = response.total
    loading.value = false

    // 更新下拉框选项
    updateSelectOptions()
  })
}

/** 刷新列表数据 */
function refreshList() {
  queryParams.value.pageNum = 1
  getList()
}

/** 更新下拉框选项 */
function updateSelectOptions() {
  // 更新机构等级选项
  const uniqueGrades = [...new Set(hospitalList.value
      .map(item => item.grade)
      .filter(grade => grade && grade.toString().trim() !== '')
  )]
  gradeOptions.value = uniqueGrades.map(grade => ({ value: grade, label: grade }))
}

// 取消按钮
function cancel() {
  open.value = false
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.hospitalId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 状态修改  */
function handleStatusChange(row, newStatus) {
  const originalStatus = row.status
  const text = newStatus === '1' ? "上架" : "下架"

  proxy.$modal.confirm('确认要' + text + ' "' + row.hospitalName + '" 吗？').then(function() {
    const updateData = {
      hospitalId: Number(row.hospitalId),
      status: newStatus
    }
    return updateHospital(updateData)
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功")
    // 更新本地数据状态
    row.status = newStatus
  }).catch(function(error) {
    console.error('状态更新失败:', error)
    // 操作失败时恢复原来的状态
    row.status = originalStatus
    proxy.$modal.msgError(text + "失败")
  })
}

/** 格式化机构类型 */
function formatHospitalType(type) {
  const typeMap = {
    1: '医院',
    2: '体检中心',
    3: '诊所'
  }
  return typeMap[type] || type
}

/** 格式化完整地址 */
function getFullAddress(row) {
  const { province, city, district, address } = row
  const addressParts = []

  if (province) addressParts.push(province)
  if (city) addressParts.push(city)
  if (district) addressParts.push(district)
  if (address) addressParts.push(address)

  return addressParts.length > 0 ? addressParts.join('') : '-'
}

/** 查看详情按钮操作 */
async function handleView(row) {
  viewOpen.value = true
  detailLoading.value = true

  try {
    console.log('开始获取机构详情，hospitalId:', row.hospitalId)
    const response = await getHospitalWithDepartments(row.hospitalId)
    console.log('详情接口响应:', response)

    if (response.code === 200) {
      // 确保数据正确赋值
      if (response.data) {
        viewForm.value = {
          ...response.data,
          // 确保 departments 字段存在
          departments: response.data.departments || []
        }
        console.log('详情数据设置完成:', viewForm.value)
        console.log('科室数据:', viewForm.value.departments)

        // 打印科室数据的详细信息
        if (viewForm.value.departments && viewForm.value.departments.length > 0) {
          console.log('科室数据详情:')
          viewForm.value.departments.forEach((dept, index) => {
            console.log(`科室${index + 1}:`, {
              departmentId: dept.departmentId,
              departmentName: dept.departmentName,
              parentId: dept.parentId,
              level: dept.level,
              levelType: typeof dept.level
            })
          })
        }
      } else {
        console.error('详情数据为空')
        proxy.$modal.msgError('获取详情失败：数据为空')
      }
    } else {
      console.error('接口返回错误:', response.msg)
      proxy.$modal.msgError('获取详情失败：' + (response.msg || '未知错误'))
    }
  } catch (error) {
    console.error('获取详情异常:', error)
    proxy.$modal.msgError('获取详情失败')
  } finally {
    detailLoading.value = false
  }
}

/** 获取分组后的科室数据 */
function getGroupedDepartments() {
  console.log('开始分组科室数据:', viewForm.value.departments)

  if (!viewForm.value.departments || viewForm.value.departments.length === 0) {
    console.log('没有科室数据')
    return []
  }

  // 获取所有一级科室和二级科室
  const primaryDepartments = []
  const secondaryDepartments = []

  // 分离一级和二级科室 - 支持字符串和数字类型的 level
  viewForm.value.departments.forEach(dept => {
    const level = dept.level
    console.log(`处理科室: ${dept.departmentName}, level: ${level}, type: ${typeof level}`)

    if (level === '1' || level === 1) {
      console.log('识别为一级科室:', dept.departmentName)
      primaryDepartments.push(dept)
    } else if (level === '2' || level === 2) {
      console.log('识别为二级科室:', dept.departmentName)
      secondaryDepartments.push(dept)
    } else {
      console.log('未知level的科室:', dept.departmentName, 'level:', level)
    }
  })

  console.log('一级科室:', primaryDepartments)
  console.log('二级科室:', secondaryDepartments)

  // 如果没有一级科室，但有二级科室，需要从二级科室中提取一级科室信息
  if (primaryDepartments.length === 0 && secondaryDepartments.length > 0) {
    console.log('没有一级科室，从二级科室中提取父级信息')

    // 获取所有不同的 parentId
    const parentIds = [...new Set(secondaryDepartments.map(dept => dept.parentId))]
    console.log('找到的父级ID:', parentIds)

    // 为每个 parentId 创建虚拟的一级科室，使用预定义名称
    parentIds.forEach(parentId => {
      const predefinedNames = {
        1: '内科',
        2: '外科',
        3: '妇产科',
        4: '儿科',
        5: '眼科',
        6: '耳鼻喉科',
        7: '口腔科',
        8: '皮肤科',
        9: '中医科',
        10: '康复科'
      }

      const primaryName = predefinedNames[parentId] || `科室${parentId}`
      primaryDepartments.push({
        departmentId: parentId,
        departmentName: primaryName,
        level: '1'
      })
    })

    console.log('创建的虚拟一级科室:', primaryDepartments)
  }

  // 如果还是没有一级科室，直接返回空
  if (primaryDepartments.length === 0) {
    console.log('仍然没有一级科室数据')
    return []
  }

  // 按一级科室分组二级科室
  const grouped = primaryDepartments.map(primaryDept => {
    const secondaryDepts = secondaryDepartments.filter(
        secondaryDept => secondaryDept.parentId === primaryDept.departmentId
    )
    console.log(`一级科室 ${primaryDept.departmentName} 下的二级科室:`, secondaryDepts)

    return {
      primaryId: primaryDept.departmentId,
      primaryName: primaryDept.departmentName,
      secondaryDepartments: secondaryDepts
    }
  })

  console.log('分组后的科室数据:', grouped)
  return grouped
}

/** 新增按钮操作 */
function handleAdd() {
  proxy.$router.push('/institution/hospital/add')
}

/** 修改按钮操作 */
function handleUpdate(row) {
  const hospitalId = row.hospitalId || ids.value[0]
  proxy.$router.push('/institution/hospital/edit/' + hospitalId)
}

/** 删除按钮操作 */
function handleDelete(row) {
  const hospitalIds = row.hospitalId || ids.value
  proxy.$modal.confirm('是否确认删除机构管理编号为"' + hospitalIds + '"的数据项？').then(function() {
    return delHospital(hospitalIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('institution/hospital/export', {
    ...queryParams.value
  }, `hospital_${new Date().getTime()}.xlsx`)
}

// 暴露刷新方法给子组件调用
window.refreshHospitalList = () => {
  getList()
}

getList()
</script>

<style scoped>
/* 简约型样式 */
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

/* 搜索面板 */
.search-panel {
  background: #fff;
  border-radius: 4px;
  padding: 18px 20px 0;
  margin-bottom: 16px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

/* 操作面板 */
.action-panel {
  background: #fff;
  border-radius: 4px;
  padding: 16px 20px;
  margin-bottom: 16px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

/* 表格面板 */
.table-panel {
  background: #fff;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 16px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

/* 分页面板 */
.pagination-panel {
  display: flex;
  justify-content: center;
  background: #fff;
  border-radius: 4px;
  padding: 16px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

/* Logo 样式 */
.logo-container {
  display: flex;
  align-items: center;
  justify-content: center;
}

.table-logo {
  width: 40px;
  height: 40px;
  border-radius: 4px;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  border-radius: 4px;
}

.no-logo {
  color: #909399;
  font-size: 12px;
}

/* 地址文本 */
.address-text {
  display: inline-block;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: default;
}

.no-address {
  color: #909399;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}

/* 详情样式 */
.detail-content {
  padding: 20px 0;
}

.logo-detail {
  display: flex;
  align-items: center;
  gap: 10px;
}

.detail-logo {
  width: 60px;
  height: 60px;
  border-radius: 4px;
}

.no-logo-detail {
  color: #909399;
}

.address-detail {
  word-break: break-all;
}

/* 科室样式 */
.departments-container {
  max-height: 200px;
  overflow-y: auto;
}

.department-group {
  display: flex;
  align-items: flex-start;
  margin-bottom: 12px;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 4px;
}

.primary-department {
  font-weight: bold;
  min-width: 100px;
  margin-right: 10px;
}

.secondary-departments {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.no-departments {
  color: #909399;
  font-style: italic;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>